package com.tungse.study.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

    public static void main(String[] args) throws InterruptedException {

        int[] count = new int[]{1000};
        List<Thread> threads = new ArrayList<>();
//         new ReentrantLock();
//        MyLock lock = new MyLock();//
        MyReentrantLock lock = new MyReentrantLock();//
        for (int i = 0; i < 2; i++) {
            threads.add(new Thread(()->{
                try {
                    for (int j = 0; j < 5; j++) {
                        lock.lock();
//                        TimeUnit.MILLISECONDS.sleep(2);
                        count[0]--;
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    for (int j = 0; j < 6; j++) {
                        lock.unlock();
                    }
                }
            }));
        }

        threads.forEach(Thread::start);
        threads.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });

//        TimeUnit.SECONDS.sleep(1);
        System.out.println(count[0]);
    }
}
